//
//  CNDisplayView.m
//  BeeQuick_19
//
//  Created by tanky on 2016/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNDisplayView.h"
#import "CNDisplayViewData.h"
#import <SDWebImage/UIButton+WebCache.h>

@interface CNDisplayView ()
@property(nonatomic,strong)NSArray *displayArray;
@end

@implementation CNDisplayView

#pragma mark View创建的时候就去获取数据
- (instancetype)init{
    [self loadFuncBtnsData];
    return [super init];
}

- (instancetype)initWithFrame:(CGRect)frame{
    [self loadFuncBtnsData];
    return [super initWithFrame:frame];
}

#pragma mark 有数据赋值的时候 就去添加buttons
- (void)setDisplayArray:(NSArray *)displayArray{
    if (_displayArray != displayArray) {
        _displayArray = displayArray;
        [self addButtonsView];
    }
}

#pragma mark 加载网络数据 并赋值
- (void)loadFuncBtnsData{
    CNHTTPSessionManager *manager = [CNHTTPSessionManager sharedManager];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    // type = 0/1
    [param setValue:@"1" forKey:@"call"];
    
    [manager request:CNHttpMethodPost componentUrlString:@"focus.json.php" parameters:param completion:^(id response, NSError *error) {
        NSArray *arr = [NSArray yy_modelArrayWithClass:[CNDisplayViewData class] json:response[@"data"][@"activities"]];
        self.displayArray = arr.copy;
    }];
}

#pragma mark 添加Buttons到屎大颗View上
- (void)addButtonsView{
    self.axis = UILayoutConstraintAxisVertical;
    self.alignment = UIStackViewAlignmentFill;
    self.spacing = 0;
    self.distribution = UIStackViewDistributionFillEqually;
    for (CNDisplayViewData *model in self.displayArray) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn sd_setImageWithURL:[NSURL URLWithString:model.img] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"v2_placeholder_full_size"]];
        [btn sizeToFit];
        btn.imageEdgeInsets = UIEdgeInsetsMake(7, 10, 7, 10);
        [self addArrangedSubview:btn];
    }
}

@end
